/*
 * Copyright (C) 2012 genzo
 */
package jp.gr.java_conf.genzo.wolrepeater;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

/**
 * MACアドレス＆IPアドレス編集.
 *
 */
public class EditItemActivity extends Activity {

    /** 編集中のアイテムのインデックス. */
    private int mEditIndex;

    /*
     * (非 Javadoc)
     *
     * @see android.app.Activity#onCreate(android.os.Bundle)
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_item);

        MachineInfo item = (MachineInfo) getIntent().getSerializableExtra(
                WolRepeaterActivity.ITEM);

        if (item == null) {
            return;
        }

        mEditIndex = getIntent()
                .getIntExtra(WolRepeaterActivity.EDIT_INDEX, -1);

        TextView ip = findView(R.id.add_edit_ip);
        TextView mac = findView(R.id.add_edit_mac);
        TextView port = findView(R.id.add_edit_port);

        ip.setText(item.getIp());
        mac.setText(item.getMac());
        port.setText(String.valueOf(item.getPort()));

    }

    /**
     * OK押下.
     *
     * @param view
     *            対象のView
     */
    public void onOkClick(View view) {

        TextView ip = findView(R.id.add_edit_ip);
        TextView mac = findView(R.id.add_edit_mac);
        TextView port = findView(R.id.add_edit_port);

        String strIp = ip.getText().toString();
        String strMac = mac.getText().toString();
        String strPort = port.getText().toString();

        if (!WolRepeaterService.checkMacAddr(strMac)) {
            Toast.makeText(this, R.string.error_mac_text, Toast.LENGTH_SHORT)
            .show();
            return;
        }
        if (!WolRepeaterService.checkIpAddr(strIp)) {
            Toast.makeText(this, R.string.error_ip_text, Toast.LENGTH_SHORT)
            .show();
            return;
        }
        if (!WolRepeaterService.checkPort(strPort)) {
            Toast.makeText(this, R.string.error_ip_text, Toast.LENGTH_SHORT)
            .show();
            return;
        }

        MachineInfo item = new MachineInfo(strMac, strIp,
                Integer.parseInt(strPort));
        Intent intent = new Intent();
        intent.putExtra(WolRepeaterActivity.ITEM, item);
        intent.putExtra(WolRepeaterActivity.EDIT_INDEX, mEditIndex);

        setResult(RESULT_OK, intent);
        finish();

    }

    /**
     *
     * View取得.
     *
     * @param <T>
     *            期待するView型
     * @param id
     *            ViewのID
     * @return 指定型のView
     */
    @SuppressWarnings("unchecked")
    private <T extends View> T findView(int id) {
        return (T) findViewById(id);
    }

}
